package com.xiaoshuidi.cloud.module.contract.controller.admin.contract;

import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.excel.core.util.ExcelUtils;
import com.xiaoshuidi.cloud.framework.operatelog.core.annotations.OperateLog;
import com.xiaoshuidi.cloud.module.contract.controller.admin.contract.vo.HomeQueryVO;
import com.xiaoshuidi.cloud.module.contract.controller.admin.contract.vo.ownerContract.*;
import com.xiaoshuidi.cloud.module.contract.convert.contract.ContractHouseOwnerConvert;
import com.xiaoshuidi.cloud.module.contract.dal.dataobject.contract.ContractHouseOwnerPropertyTemplateDO;
import com.xiaoshuidi.cloud.module.contract.service.contract.ContractHouseOwnerService;
import com.xiaoshuidi.cloud.module.contract.service.home.HomeService;
import com.xiaoshuidi.cloud.module.contract.util.date.DateEntity;
import com.xiaoshuidi.cloud.module.contract.util.date.DateUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.xiaoshuidi.cloud.framework.common.pojo.CommonResult.success;
import static com.xiaoshuidi.cloud.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.xiaoshuidi.cloud.module.contract.enums.ApiConstants.ZERO;

@Tag(name = "管理后台 - 业主合同")
@RestController
@RequestMapping("/contract/house-owner")
@Validated
public class ContractHouseOwnerController {

    @Resource
    private ContractHouseOwnerService houseOwnerService;
    @Resource
    private HomeService homeService;

    @PostMapping("/create")
    @Operation(summary = "创建业主合同")
//    @PreAuthorize("@ss.hasPermission('contract:owner:create')")
    public CommonResult<Long> createHouseOwner(@Valid @RequestBody ContractHouseOwnerCreateReqVO createReqVO) {
        return success(houseOwnerService.createHouseOwner(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新业主合同")
//    @PreAuthorize("@ss.hasPermission('contract:owner:update')")
    public CommonResult<Boolean> updateHouseOwner(@Valid @RequestBody ContractHouseOwnerUpdateReqVO updateReqVO) {
        houseOwnerService.updateHouseOwner(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除业主合同")
    @Parameter(name = "id", description = "编号", required = true)
    @Parameter(name = "deleteBill", description = "删除订单流水", required = true)
//    @PreAuthorize("@ss.hasPermission('contract:owner:delete')")
    public CommonResult<Boolean> deleteHouseOwner(@RequestParam("id") Long id, @RequestParam("deleteBill") Boolean deleteBill) {
        houseOwnerService.deleteHouseOwner(id, deleteBill);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得业主合同详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('contract:owner:query')")
    public CommonResult<ContractHouseOwnerRespVO> getHouseOwner(@RequestParam("id") Long id) {
        ContractHouseOwnerRespVO houseOwnerResp = houseOwnerService.getHouseOwnerResp(id);
        return success(houseOwnerResp);
    }

    @GetMapping("/page")
    @Operation(summary = "获得业主合同分页")
//    @PreAuthorize("@ss.hasPermission('contract:owner:query')")
    public CommonResult<PageResult<ContractHouseOwnerPageRespVO>> getHouseOwnerPage(@Valid ContractHouseOwnerPageReqVO pageVO) {
        return success(houseOwnerService.getHouseOwnerPage(pageVO));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出业主合同 Excel")
//    @PreAuthorize("@ss.hasPermission('contract:owner:export')")
    @OperateLog(type = EXPORT)
    public void exportHouseOwnerExcel(@Valid ContractHouseOwnerPageReqVO pageVO,
              HttpServletResponse response) throws IOException {
       /* List<ContractHouseOwnerPageRespVO> list = houseOwnerService.getExportHouseOwnerList(pageVO);
        // 导出 Excel
        List<ContractHouseOwnerExcelVO> datas = ContractHouseOwnerConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "业主合同.xls", "数据", ContractHouseOwnerExcelVO.class, datas);*/
        pageVO.setPageSize(100);
        PageResult<ContractHouseOwnerPageRespVO> pageResult = houseOwnerService.getHouseOwnerPage(pageVO);
        ExcelUtils.write(response, "业主合同.xlsx", "数据", ContractHouseOwnerExcelVO.class, pageResult,
                ContractHouseOwnerConvert.INSTANCE::convertList02, (pageNo) -> {
                    pageVO.setPageNo(pageNo);
                    return houseOwnerService.getHouseOwnerPage(pageVO);
                });
    }

    @GetMapping("/free-period-year")
    @Operation(summary = "获取免租期年份差")
    @Parameters({
            @Parameter(name = "startTime", description = "开始时间", required = true),
            @Parameter(name = "endTime", description = "结束时间", required = true)
    })
//    @PreAuthorize("@ss.hasPermission('contract:owner:create')")
    public CommonResult<Integer> getFreePeriod(@RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern(DateUtils.FORMAT_DATE);
        LocalDate startDate = LocalDate.parse(startTime, fmt);
        LocalDate endDate = LocalDate.parse(endTime, fmt);
        DateEntity dateEntity = DateUtils.calculateTimeBetween(startDate, endDate);
        if (Objects.isNull(dateEntity)){
            return success(ZERO);
        }
        if (dateEntity.getMonth() > 0 || dateEntity.getDay() > 0){
            return success(dateEntity.getYear() + 1);
        }else {
            return success(dateEntity.getYear());
        }
    }

    @GetMapping("/get-renewal-contract")
    @Operation(summary = "获得业主续租合同")
    @Parameter(name = "id", description = "要续租的合同编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('contract:owner:renewal')")
    public CommonResult<ContractHouseOwnerRespVO> getRenewalContract(@RequestParam("id") Long id) {
        ContractHouseOwnerRespVO houseOwnerResp = houseOwnerService.getRenewalContract(id);
        return success(houseOwnerResp);
    }

    @PostMapping("/eviction")
    @Operation(summary = "业主合同退租")
//    @PreAuthorize("@ss.hasPermission('contract:owner:cancel')")
    public CommonResult<Boolean> evictionOwnerContract(@Valid @RequestBody ContractHouseOwnerCancelReqVO reqVo) {
        houseOwnerService.evictionOwnerContract(reqVo);
        return success(true);
    }

    @PostMapping("/cancel-renewal")
    @Operation(summary = "业主合同取消")
//    @PreAuthorize("@ss.hasPermission('contract:owner:cancel')")
    public CommonResult<Boolean> cancelContract(Long id) {
        houseOwnerService.cancelContract(id);
        return success(true);
    }

    /**
     * 获得首页业主合同分页
     */
    @GetMapping("/home-page")
    @Operation(summary = "获得首页业主合同分页")
//    @PreAuthorize("@ss.hasPermission('contract:owner:query')")
    public CommonResult<ContractOwnerHomeDataVO> getHomeHouseOwnerPage(@Valid HomeQueryVO queryDTO) {
        ContractOwnerHomeDataVO result = new ContractOwnerHomeDataVO();
        result.setPageResult(houseOwnerService.getHouseOwnerHomePage(queryDTO));
        result.setHomeData(homeService.getHomeData(queryDTO));
        return success(result);
    }


    /**
     * 业主合同续租判断
     */
    @GetMapping("/check-renewal")
    public CommonResult<Boolean> checkRenewal(@Valid @RequestParam("id") Long id) {
        return success(houseOwnerService.checkRenewal(id));
    }


    @PutMapping("/update-card-info")
    @Operation(summary = "更新业主合同银行卡信息")
//    @PreAuthorize("@ss.hasPermission('contract:owner:update')")
    public CommonResult<Boolean> updateHouseOwnerCard(@Valid @RequestBody ContractHouseOwnerCardUpdateReqVO updateReqVO) {
        houseOwnerService.updateHouseOwnerCard(updateReqVO);
        return success(true);
    }


    /**
     * 业主合同业主资产信息初始数据
     */
    @GetMapping("/owner-property-template-list")
    public CommonResult<Map<String, List<ContractHouseOwnerPropertyTemplateDO>>> ownerPropertyTemplateList(@Valid @RequestParam("apartmentId") Long apartmentId) {
        List<ContractHouseOwnerPropertyTemplateDO> templateDOS = houseOwnerService.ownerPropertyTemplateList(apartmentId);
        if (CollectionUtils.isNotEmpty(templateDOS)){
            Map<String, List<ContractHouseOwnerPropertyTemplateDO>> result = new HashMap<>();
            templateDOS.forEach(t ->{
                if (t.getType() == 0){
                    List<ContractHouseOwnerPropertyTemplateDO> property;
                    if (result.containsKey("property")){
                        property = result.get("property");
                        property.add(t);
                    }else {
                        property = new ArrayList<>();
                        property.add(t);
                    }
                    result.put("property", property);
                }else if (t.getType() == 1){
                    List<ContractHouseOwnerPropertyTemplateDO> furniture;
                    if (result.containsKey("furniture")){
                        furniture = result.get("furniture");
                        furniture.add(t);
                    }else {
                        furniture = new ArrayList<>();
                        furniture.add(t);
                    }
                    result.put("furniture", furniture);
                }
            });
            return success(result);
        }
        return success(null);
    }

    /**
     * 业主合同变更管家
     */
    @PostMapping("/change-house-keep")
    public CommonResult<Boolean> changeHousekeep(@Valid @RequestBody ChangeHousekeepReqVO reqVO) {
        return success(houseOwnerService.changeHousekeep(reqVO));
    }

}
